package com.xoa.service.crm.impl;


import com.xoa.dao.crm.SupplierMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.crm.Supplier;
import com.xoa.model.crm.SupplierExample;
import com.xoa.model.users.Users;
import com.xoa.service.crm.SupplierService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.ExcelUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Service
public class SupplierServiceImpl  implements SupplierService {

    @Autowired
    private SupplierMapper supplierMapper;
    @Autowired
    private UsersMapper usersMapper;
    /**
     * 查询所有 模糊查询
     * @param map
     * @return
     */
    @Override
    public List<Supplier> selectByCondition(Integer page, Integer pageSize, Boolean useFlag, Map map) {

        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        map.put("page", pageParams);

        return  supplierMapper.selectByCondition(map);
    }

    /**
     * 添加一条供应商数据
     * @param supplier
     * @return
     */
    public int insert(Supplier supplier){

        //创建时间
        supplier.setCreateTime(new Date());

        //获取登录用户
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
    Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);
    //创建人userId
        supplier.setCreator(users.getUserId());

    //数据默认为未删除
        supplier.setIsDeleted(Byte.valueOf("0"));
        return supplierMapper.insert(supplier);
}

    /**
     * 数据回显
     * @param supplierId
     * @return
     */
    @Override
    public Supplier selectByPrimaryKey(Integer supplierId) {
        Supplier supplier = supplierMapper.selectByPrimaryKey(supplierId);
        Users userId = usersMapper.getUserId(supplier.getCreator());
        supplier.setCreator(userId.getUserName());
        return supplier;
    }

    /**
     * 修改供应商数据
     * @param supplier
     * @return
     */
    @Override
    public int updateByPrimaryKey(Supplier supplier) {

        //获取登录用户
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);

        //更新人的userId
        supplier.setUpdator(users.getUserId());

        //更新时间
        supplier.setUpdateTime(new Date());
        return supplierMapper.updateByPrimaryKeySelective(supplier);
    }

    /**
     * 根据id删除
     * @param supplierId
     * @return
     */
    @Override
    public int deleteByPrimaryKey(Integer supplierId) {

        //获取登录用户
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);
        //逻辑删除 修改状态
        Supplier supplier = supplierMapper.selectByPrimaryKey(supplierId);
        supplier.setIsDeleted(Byte.valueOf("1"));
        //删除人
        supplier.setDeleteUser(users.getUserId());
        //删除时间
        supplier.setDeleteTime(new Date());
        return supplierMapper.updateByPrimaryKeySelective(supplier);
    }

    /**
     * 导出功能
     * @param request
     * @param response
     * @return
     */
    @Override
    public ToJson<Supplier> supplierExport(HttpServletRequest request, HttpServletResponse response) {

        ToJson<Supplier> json = new ToJson<Supplier>();


        try {

            SupplierExample supplierExample = new SupplierExample();
            supplierExample.createCriteria().andIsDeletedEqualTo(Byte.valueOf("0"));
            List<Supplier> suppliers = supplierMapper.selectByExample(supplierExample);

            HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("供应商管理表", 9);
            String[] secondTitles = {"供应商名称", "供应商电话", "传真号码", "供应商网址", "邮政编码","电子邮箱","供应商地址","所在地区（省）",
                    "所在地区 （市）","开户行","银行账号","户名","备注"};



            HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);

            String[] beanProperty = {"supplierName", "phone", "fax", "website", "zipCode","email","address","province","city",
                    "registerBank","bankAccount","accountName","remark"};


            HSSFWorkbook workbook = ExcelUtil.exportExcelData(workbook2, suppliers, beanProperty);
            ServletOutputStream out = response.getOutputStream();

            String filename = "供应商管理表.xls";
            filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-disposition", "attachment;filename=" + filename);
            workbook.write(out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;
    }

    /**
     * 导入功能
     * @param request
     * @param response
     * @param file
     * @return
     */
    @Override
    public ToJson<Supplier> insertImport(HttpServletRequest request, HttpServletResponse response, MultipartFile file) {
        File dest = null;
        ToJson<Supplier> json = new ToJson<Supplier>();
        InputStream in=null;
        try {

            //判读当前系统
            //读取配置文件
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            String osName = System.getProperty("os.name");
            StringBuffer stringBuffer = new StringBuffer();
            StringBuffer buffer = new StringBuffer();
            if (osName.toLowerCase().startsWith("win")) {
                //sb=sb.append(rb.getString("upload.win"));
                //判断路径是否是相对路径，如果是的话，加上运行的路径
                String uploadPath = rb.getString("upload.win");
                if (uploadPath.indexOf(":") == -1) {
                    //获取运行时的路径
                    String basePath = this.getClass().getClassLoader().getResource(".").getPath() + File.pathSeparator;
                    //获取截取后的路径
                    String str2 = "";
                    if (basePath.indexOf("/xoa") != -1) {
                        //获取字符串的长度
                        int length = basePath.length();
                        //返回指定字符在此字符串中第一次出现处的索引
                        int index = basePath.indexOf("/xoa");
                        //从指定位置开始到指定位置结束截取字符串
                        str2 = basePath.substring(0, index);
                    }
                    stringBuffer = stringBuffer.append(str2 + "/xoa");
                }
                stringBuffer.append(uploadPath);
                buffer = buffer.append(rb.getString("upload.win"));
            } else {
                stringBuffer = stringBuffer.append(rb.getString("upload.linux"));
                buffer = buffer.append(rb.getString("upload.linux"));
            }
            // 判断是否为空文件
            if (file.isEmpty()) {
                json.setMsg("请上传文件！");
                json.setFlag(1);
                return json;
            } else {
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    int pos = fileName.indexOf(".");
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File pathfile = new File(String.valueOf(stringBuffer));
                    if (!pathfile.exists()) {// 如果目录不存在
                        pathfile.mkdirs();// 创建文件夹
                    }
                    dest = new File(stringBuffer.toString(), newFileName);
                    file.transferTo(dest);
                    // 将文件上传成功后进行读取文件
                    // 进行读取的路径
                    String readPath = stringBuffer.append(System.getProperty("file.separator")).append(newFileName).toString();
                    in = new FileInputStream(readPath);
                    HSSFWorkbook workbook = new HSSFWorkbook(in);
                    HSSFSheet sheet = workbook.getSheetAt(0);




                    //3、读取行
                    if(sheet.getPhysicalNumberOfRows() > 2){
                        Supplier supplier = null;
                        for(int k = 2; k < sheet.getPhysicalNumberOfRows(); k++){
                            //4、读取单元格
                            HSSFRow row = sheet.getRow(k);
                            supplier = new Supplier();

                            if (row.getCell(0) != null  && row.getCell(0).getStringCellValue() !="") {


                                //供应商名称
                                row.getCell(0).setCellType(CellType.STRING);
                                supplier.setSupplierName(row.getCell(0).getStringCellValue());

                                if (row.getCell(1) != null) {
                                    //供应商电话
                                    row.getCell(1).setCellType(CellType.STRING);
                                    supplier.setPhone(row.getCell(1).getStringCellValue());
                                }

                                //传真号码
                                row.getCell(2).setCellType(CellType.STRING);
                                supplier.setFax(row.getCell(2).getStringCellValue());
                                //供应商网址
                                row.getCell(3).setCellType(CellType.STRING);
                                supplier.setWebsite(row.getCell(3).getStringCellValue());
                                //邮政编码
                                row.getCell(4).setCellType(CellType.STRING);
                                supplier.setZipCode(row.getCell(4).getStringCellValue());
                                //电子邮箱
                                row.getCell(5).setCellType(CellType.STRING);
                                supplier.setEmail(row.getCell(5).getStringCellValue());
                                //供应商地址
                                row.getCell(6).setCellType(CellType.STRING);
                                supplier.setAddress(row.getCell(6).getStringCellValue());
                                //所在地区（省）
                                row.getCell(7).setCellType(CellType.STRING);
                                supplier.setProvince(row.getCell(7).getStringCellValue());
                                //所在地区（市）
                                row.getCell(8).setCellType(CellType.STRING);
                                supplier.setCity(row.getCell(8).getStringCellValue());
                                //开户行
                                row.getCell(9).setCellType(CellType.STRING);
                                supplier.setRegisterBank(row.getCell(9).getStringCellValue());
                                //银行账号
                                row.getCell(10).setCellType(CellType.STRING);
                                supplier.setBankAccount(row.getCell(10).getStringCellValue());
                                //户名
                                row.getCell(11).setCellType(CellType.STRING);
                                supplier.setAccountName(row.getCell(11).getStringCellValue());
                                //备注
                                row.getCell(12).setCellType(CellType.STRING);
                                supplier.setRemark(row.getCell(12).getStringCellValue());

                                //默认为未删除
                                supplier.setIsDeleted(Byte.valueOf("0"));

                                //获取登录用户
                                Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
                                Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
                                //创建人
                                supplier.setCreator(users.getUserId());

                                //创建时间
                                supplier.setCreateTime(new Date());

                                //5、保存供应商数据
                                supplierMapper.insert(supplier);
                            }
                        }
                    }

                    json.setFlag(0);
                    json.setMsg("ok");
                    dest.delete();
                } else {
                    json.setMsg("文件类型不正确！");
                    json.setFlag(1);
                    return json;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("数据保存异常");
            json.setFlag(1);
        } finally {
            dest.delete();
            try {
                if(in!=null){
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return json;
    }
}
